package com.example.applicationview.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.applicationview.R;
import com.example.applicationview.bean.PieData;

import java.util.ArrayList;
/**
 * 扇形图练习
 */
public class PieView2 extends View {
    // 颜色表 (注意: 此处定义颜色使用的是ARGB，带Alpha通道的)
    private int[] mColors = {0xFFCCFF00, 0xFF6495ED, 0xFFE32636, 0xFF800000, 0xFF808000, 0xFFFF8C69, 0xFF808080,
            0xFFE6B800, 0xFF7CFC00};
    // 饼状图初始绘制角度
    private float mStartAngle = 0;
    // 数据
    private ArrayList<PieData> mData;
    // 宽高
    private int mWidth, mHeight;
    // 画笔
    private Paint mPaint = new Paint();
    // 画笔
    private Paint textPaint = new Paint();

    public PieView2(Context context) {
        this(context, null);
    }

    public PieView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //初始化画笔
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        textPaint.setAntiAlias(true);
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setColor(getResources().getColor(R.color.black));
        textPaint.setTextSize(20);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //获取宽高
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mData == null)
            return;
        canvas.translate(mWidth / 2, mHeight / 2);                // 将画布坐标原点移动到中心位置
        float r = (float) (Math.min(mWidth, mHeight) / 2 * 0.8);  // 饼状图半径
        RectF rect = new RectF(-r, -r, r, r);

        //画每一个扇形区域
        float num = mStartAngle;
        for (int i = 0; i < mData.size(); i++) {
            PieData data = mData.get(i);
            mPaint.setColor(data.getColor());
            canvas.drawArc(rect, num, data.getAngle(), true, mPaint);
            num += data.getAngle();

        }

    }

    //设置开始角度
    public void setStartAngle(float mStartAngle) {
        this.mStartAngle = mStartAngle;
    }

    public void setData(ArrayList<PieData> mData) {
        initData(mData);
        invalidate();   // 刷新
    }

    private void initData(ArrayList<PieData> mData) {
        //1,计算数值和,
        int num = 0;
        for (PieData data: mData) {
            num+= data.getValue();
        }
        //2,设置颜色 3，设置百分比， 4,角度
        for (int i = 0; i < mData.size(); i++) {
            PieData data = mData.get(i);
            data.setColor(mColors[i]);
            float percentage = data.getValue()/ num;
            data.setPercentage(percentage);
            data.setAngle(percentage * 360);
        }
        this.mData = mData;
    }


}
